// function hashFunc (str, max) {
//     var hashCode = 0
//     for (var i = 0; i < str.length; i++) {
//         hashCode = 37 * hashCode + str.charCodeAt(i)
//         console.log('hashCode----', hashCode);
//     }
//     hashCode = hashCode % max
//     return hashCode
// }
// console.log(hashFunc("abc", 7)) // 4
// console.log(hashFunc("cba", 7)) // 3
// console.log(hashFunc("nba", 7)) // 5
// console.log(hashFunc("mba", 7)) // 1


var arr = []
arr[7] = undefined
function HashTable() {
    this.storage = []
    this.count = 0
    this.limit = 8
    // 哈希函数
    HashTable.prototype.hashFunc = function (str, max) {
        var hashCode = 0
        for (var i = 0; i < str.length; i++) {
            hashCode = 37 * hashCode + str.charCodeAt(i)
        }
        // 取模运算
        hashCode = hashCode % max
        return hashCode
    }
    // 哈希表添加
    HashTable.prototype.push = function (key, value) {
        // 获取key对应的index
        var index = this.hashFunc(key, this.limit)
        // 取出数组
        var bucket = this.storage[index]
        if (bucket === undefined) {
            bucket = []
            this.storage[index] = bucket
        }
        var override = false
        for (var i = 0; i < bucket.length; i++) {
            var tuple = bucket[i]
            if (tuple[0] === key) {
                tuple[1] = value
                override = true
            }
        }
        if (!override) {
            bucket.push([key, value])
            this.count++
        }
    }
    // 根据key获取value
    HashTable.prototype.get = function (key) {
        var index = this.hashFunc(key, this.limit)
        var bucket = this.storage[index]
        if (bucket == null) {
            return null
        }
        for (let i = 0; i < bucket.length; i++) {
            var tuple = bucket[i]
            if (tuple[0] === key) {
                return tuple[1]
            }
        }
        return null
    }
    // 删除
    HashTable.prototype.remove = function (key) {
        var index = this.hashFunc(key, this.limit)
        var bucket = this.storage[index]
        if (bucket == null) {
            console.log('元素不存在');
            return null
        }
        for (let i = 0; i < bucket.length; i++) {
            var tuple = bucket[i]
            if (tuple[0] === key) {
                bucket.splice(i, 1)
                this.count--
                return tuple[1]
            }
            console.log('元素的value不存在');
            return null
        }
    }
    // isEmpty方法
    HashTable.prototype.isEmpty = function () {
        return this.count == 0
    }
    // size方法
    HashTable.prototype.size = function () {
        return this.count
    }
}

var ht = new HashTable()

ht.push("abc", "123")
ht.push("cba", "321")
ht.push("nba", "521")
ht.push("abc", '333')
ht.remove("abc")
ht.remove("bbc")
ht.remove("abc")
console.log(ht.get('abc'));
console.log(ht.get('nba'));
// ht.push("mba", "520")
console.log(ht);
// console.log('ht-------', Object.values(ht));